package com.zdp.contentcenter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zdp.contentcenter.dao.content.ShareMapper;
import com.zdp.contentcenter.domain.dto.user.UserDTO;
import com.zdp.contentcenter.domain.entity.content.Share;
import com.zdp.contentcenter.feignclient.TestBaiduFeignClient;
import com.zdp.contentcenter.service.content.TestSentinelService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @author sesshomaru
 * @date 2020/9/16 23:13
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@RestController
public class TestController {

    private final ShareMapper shareMapper;

    private final DiscoveryClient discoveryClient;

    @GetMapping("/test")
    public List<Share> testInsert() {
        Share share = new Share();
        share.setCreateTime(new Date());
        share.setUpdateTime(new Date());
        share.setTitle("xxx");
        share.setCover("xxx");
        this.shareMapper.insertSelective(share);

        List<Share> shares = this.shareMapper.selectAll();
        return shares;
    }

    @GetMapping("/test2")
    public List<ServiceInstance> setDiscoveryClient() {
        // 查询指定服务id的实例信息
        return this.discoveryClient.getInstances("user-center");
    }

 /*
 测试feign多参数请求
 @Autowired
    private TestUserCenterFeignClient testUserCenterFeignClient;
    @GetMapping("test-get")
    public UserDTO query(UserDTO userDTO){
        return testUserCenterFeignClient.query(userDTO);
    }*/

    @Autowired
    private TestBaiduFeignClient baiduFeignClient;

    @GetMapping("baidu")
    public String baiduIndex() {
        return baiduFeignClient.index();
    }

    @Autowired
    private TestSentinelService testSentinelService;

    @GetMapping("test-a")
    public String testa(){
        testSentinelService.common();
        return "test-a";
    }

    @GetMapping("test-b")
    public String testb(){
        testSentinelService.common();
        return "test-b";
    }

    @GetMapping("test-hot")
    @SentinelResource("hot")
    public String testHot(@RequestParam(required = false) String a,
                          @RequestParam(required = false) String b){
        return a + " "+ b;
    }

    @GetMapping("test-sentinel-resource")
    @SentinelResource(value = "test-sentinel-resource",
            blockHandler = "block",
            fallback = "fallback")
    public String testSentinelResource(@RequestParam(required = false) String a){
        if (StringUtils.isBlank(a)) {
            throw new IllegalArgumentException("a不能为空");
        }
        return a;
    }
    /**
     * 处理限流或者降级
     * @param a
     * @param e
     * @return
     */
    // blockHandler方法必须与原方法(testSentinelResource)参数一致
    public String block(String a, BlockException e){
        log.warn("限流或者降级", e);
        return "限流或者降级";
    }

    // 只处理降级
    public String fallback(String a){
        log.warn("降级了");
        return "降级了";
    }

    // 测试sentinel api
    @GetMapping("test-sentinel-api")
    public String testSentinelApi(@RequestParam(required = false) String a){
        String resourceName = "test-sentinel-api";
        Entry entry = null;
        // 第一个是被监控的资源名称 第二个参数是配置的来源
        // 只有test-wf这个来源的才会被限流或降级别的来源则不会
        ContextUtil.enter(resourceName, "test-wfw");
        try {
            // 定义sentinel保护的资源名，名称是test-sentinel-api
            entry = SphU.entry(resourceName);
            // 被保护的业务逻辑
            if (StringUtils.isBlank(a)) {
                throw new IllegalArgumentException("a不能为空");
            }
            return a;
        }
        catch (IllegalArgumentException e2) {
            // 统计IllegalArgumentException 【发生的次数、发生的占比】
            // sentinel的api默认只会对处理掉BlockException和BlockException子类的异常并会对其他异常进行监控
            // 所以需要通过Tracer来记录其他异常的异常数和异常比例然后交给sentinel的异常处理来统一控制
            Tracer.trace(e2);
            return "参数非法";
        }
        // BlockException 如果被保护的资源被限流或者降级了就会抛出这个异常
        catch (BlockException e) {
            log.warn("限流或者被降级了");
            return "限流或者被降级了";
        }
        finally {
            if (entry != null) {
                // 退出
                entry.exit();
            }
            ContextUtil.exit();
        }
    }
}
